package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.MessageConst;
import com.itheima.common.RedisConst;
import com.itheima.entity.Result;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;
/**
* @Author : wangjie
* @CreateDate : 2020/4/6 17:08
* @Version : 1.0
* @Description : 订单前端控制器
*/
@RestController
@RequestMapping("mobile/order")
@Slf4j
public class OrderController {
    //依赖注入jedispool
    @Autowired
    private JedisPool jedisPool;
    //依赖注入orderService
    @Reference
    private OrderService orderService;

    @RequestMapping("submit")
    public Result submit(@RequestBody Map<String,String> map){
        log.debug("sumit:{}"+map);
        try {
            //获取客户端发送的信息
            String telephone = map.get("telephone");
            String validateCode = map.get("validateCode");
            //获取redis中的验证码
            Jedis jedis = jedisPool.getResource();
            String codeInRedis = jedis.get(telephone + RedisConst.SENDTYPE_LOGIN);
            //比对验证码是否一样
            if (codeInRedis==null||!codeInRedis.equals(validateCode)){
                return new Result(false, MessageConst.VALIDATECODE_ERROR);
            }
            //调用service方法 保存订单信息
            Result result= orderService.addOrder(map);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"预约失败");
        }
    }

    /**
     * 预约成功信息的展示
     * @param id
     * @return
     */
    @RequestMapping("findById")
    public Result findById(Integer id){
        try {
            Map map= orderService.findById(id);
            return new Result(true,MessageConst.ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"预约失败");
        }
    }
}
